<template>
  
  <div class="center-container">
    <t-card bordered :style="{ width: '400px' }">
      <div>
        <img src="../assets/放大镜2.jpg" alt="" style="width: 100%; height: 50%; object-fit: cover;">
      </div>
      <t-form :rules="rules" :data="formData" :colon="true" :label-width="0" @reset="onReset" @submit="onSubmit">
        <t-form-item name="account">
          <t-input v-model="formData.account" clearable placeholder="请输入账户名">
            <template #prefix-icon>
              <desktop-icon />
            </template>
          </t-input>
        </t-form-item>

        <t-form-item name="password">
          <t-input v-model="formData.password" type="password" clearable placeholder="请输入密码">
            <template #prefix-icon>
              <lock-on-icon />
            </template>
          </t-input>
        </t-form-item>

        <t-form-item>
          <t-button theme="success" type="submit" block>登录</t-button>
        </t-form-item>
      </t-form>
    </t-card>
  </div>

</template>
<script lang="ts" setup>
  import request from '@/utils/request';
  import { reactive } from 'vue';
  import { useRouter } from 'vue-router'
  import { MessagePlugin, type FormProps } from 'tdesign-vue-next';
  import { DesktopIcon, LockOnIcon } from 'tdesign-icons-vue-next';


  // 定义验证规则
  const rules = {
    account: [
      { required: true, message: '账号不能为空', trigger: 'blur' }, // 失去焦点时验证
    ],
    password: [
      { required: true, message: '密码不能为空', trigger: 'blur' },
    ],
  };

  const formData: FormProps['data'] = reactive({
    account: '',
    password: '',
  });
  const onReset: FormProps['onReset'] = () => {
    MessagePlugin.success('重置成功');
  };
  
  const router = useRouter() // 获取路由实例
  const onSubmit: FormProps['onSubmit'] = async ({ validateResult, firstError }) => {
    if (validateResult === true) {
      // 前端用 btoa 加密（Base64）
      const encryptedPassword = btoa(formData.password)
      const response = await request.post('pax/login/', {
        "username": formData.account,
        "password": encryptedPassword,
      });
      const data = response;
      if (data.success){
        localStorage.setItem('pax_token', data.token);
        MessagePlugin.success('登录成功');
        router.push('/home/pax')  // 跳转到邮件界面
      }else{
        MessagePlugin.error(`登录失败（${data.error_msg}）`);
      }
      
    } else {
      MessagePlugin.warning(firstError);
    }
  };
</script>

<style>
.center-container {
  display: flex;           /* 启用 Flex 布局 */
  justify-content: center; /* 水平居中 */
  align-items: center;     /* 垂直居中 */
  height: 100vh;           /* 占满整个视口高度（可选） */
}
</style>
